<template>
  <div class="text-crd">
    <el-card class="editor-card">
      <template #header>
        <div class="card-header">
          <span>CRD 文本编辑器</span>
          <el-button type="primary" @click="importYaml">导入 YAML</el-button>
        </div>
      </template>
      <div ref="editorContainer" class="editor-container"></div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { invoke } from '@tauri-apps/api/core'

const emit = defineEmits(['crd-change'])

const staticCrd = `
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: samples.example.com
spec:
  group: example.com
  versions:
    - name: v1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                foo:
                  type: string
                  x-descriptors:
                    - urn:alm:descriptor:com.tectonic.ui:field
                bar:
                  type: integer
                  x-descriptors:
                    - urn:alm:descriptor:com.tectonic.ui:hidden
                nested:
                  type: object
                  properties:
                    baz:
                      type: boolean
`

const editorContainer = ref<HTMLElement | null>(null)
let monaco: any = null
let editor: any = null

onMounted(async () => {
  if (editorContainer.value) {
    if (!monaco) {
      monaco = (await import('monaco-editor'))
    }
    editor = monaco.editor.create(editorContainer.value, {
      value: staticCrd,
      language: 'yaml',
      theme: 'vs-dark',
      readOnly: true,
      minimap: { enabled: true },
      automaticLayout: true
    })
    emit('crd-change', staticCrd)
  }
})

onBeforeUnmount(() => {
  if (editor) {
    editor.dispose()
  }
})

const importYaml = async () => {
  try {
    const result = await invoke('open_file_dialog')
    if (result && editor) {
      editor.setValue(result as string)
      emit('crd-change', result as string)
    }
  } catch (error) {
    console.error('Failed to import YAML:', error)
  }
}
</script>

<style lang="scss" scoped>
.text-crd {
  height: 100%;
  
  .editor-card {
    height: 100%;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .editor-container {
      height: calc(50vh - 120px);
      min-height: 200px;
    }
  }
}
</style> 